import { useForm } from "antd/lib/form/Form";
import { Form, Modal, Input, Button } from "antd";
import { useEffect } from "react";
import { useDeleteTask, useEditTask } from "server";
import { useTasksModal } from "./util";
import UserSelect from "components/user-select";
import TaskTypeSelect from "components/task-type-select";

const TaskModal = () => {
  const [form] = useForm();
  const { editingTaskId, editingTask, close } = useTasksModal();
  const { mutateAsync: editTask, isLoading: editLoading } = useEditTask();
  const { mutateAsync: deleteTask } = useDeleteTask();

  const onCancel = () => {
    close();
    setTimeout(form.resetFields, 500);
  };

  const onOk = async () => {
    await editTask({ ...editingTask, ...form.getFieldsValue() });
    onCancel();
  };

  const startDeleteTask = () => {
    onCancel();
    Modal.confirm({
      okText: "确定",
      cancelText: "取消",
      title: "确定删除任务吗?",
      onOk: () => {
        return deleteTask(Number(editingTaskId));
      },
    });
  };

  useEffect(() => {
    form.setFieldsValue(editingTask);
  }, [form, editingTask]);

  return (
    <Modal
      title="编辑任务"
      okText="确认"
      cancelText="取消"
      confirmLoading={editLoading}
      visible={!!editingTaskId}
      onCancel={onCancel}
      onOk={onOk}
      forceRender
    >
      <Form initialValues={editingTask} form={form} layout="vertical">
        <Form.Item
          label="任务名称"
          name="name"
          rules={[{ required: true, message: "请输入任务名" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="经办人" name="processorId">
          <UserSelect defaultOptionName="经办人" />
        </Form.Item>
        <Form.Item label="类型" name="typeId">
          <TaskTypeSelect defaultOptionName="类型" />
        </Form.Item>
      </Form>
      <div style={{ textAlign: "right" }}>
        <Button onClick={startDeleteTask}>删除</Button>
      </div>
    </Modal>
  );
};

export default TaskModal;
